import React, { useState, useMemo, useEffect } from 'react'
import { useNetwork, useInterval } from 'ahooks'

import videoStore from '../../store/video'
import VideoMask from './video-mask'
import useSubs from '../../hooks/useSubs'
import common from '../../store/common'

const VideoInfo = () => {
  const { event$ } = common

  const [list, setList] = useState([])
  const [screenId, setScreenId] = useState(null)
  const [netInfo, setNewInfo] = useState({ rtt: 0, downlink: 0 })
  const [interval, setInterval] = useState(1000)

  const networkState = useNetwork()

  useEffect(() => {
    if (screenId) {
      const el = getElementById()
      el.style.display = 'block'
      setList(setData())
    }
  }, [screenId])

  useInterval(() => {
    const { rtt, downlink } = networkState
    setNewInfo({ rtt, downlink })
  }, interval)

  useSubs(({ action, val }) => {
    if (action === 'showVideoInfo') {
      setScreenId(val)
    }
  })

  function handleClick(target) {
    target.parentElement.parentElement.style.display = 'none'
  }

  function getElementById() {
    return document.getElementById(screenId).firstChild.firstChild
  }

  function setData() {
    const screen = videoStore.findScreenById(screenId)

    const player = screen?.player
    if (player) {
      const playerInfo = `xgplayer ${player?.version}`

      const video = player.video
      const { videoWidth, videoHeight, duration } = video
      const videoInfo = `${videoWidth}x${videoHeight} ${duration}s`

      const { rtt, downlink } = netInfo
      const networkInfo = `${rtt}ms ${downlink}MB/s`

      return [
        {
          label: 'Player Info：',
          value: playerInfo,
        },
        {
          label: 'Video Info：',
          value: videoInfo,
        },
        {
          label: 'Netword Info：',
          value: networkInfo,
        },
      ]
    } else {
      return []
    }
  }
  return <VideoMask data={list} handleClick={handleClick} />
}

export default VideoInfo
